﻿using Neo4jClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsApp1
{
    internal class Neo4JTableReader
    {
        public string TableName { get; set; }
        public BoltGraphClient Client { get; set; }
        public Neo4JTableReader()
        {

        }
        public DataTable GetRelationsAsDataTable()
        {
            try
            {
                // 查询指定标签的节点与其他节点的关系
                var result = Client.Cypher.Match($"(n:{TableName})-[r]->(m)")
                                    .Return((n, r, m) => new
                                    {
                                        StartNode = n.As<string>(),
                                        RelationshipType = r.Type(), // 获取关系类型
                                        Relationship = r.As<string>(),
                                        EndNode = m.As<string>(),
                                        EndNodeType = m.Labels() // 获取目标节点的标签
                                    })
                                    .ResultsAsync.Result;

                // 这里可以添加处理关系结果的逻辑，例如显示在界面上
                // 示例：将关系信息输出到控制台
                var dt = new DataTable();
                dt.Columns.Add("StartNodeType");
                dt.Columns.Add("StartNode");
                dt.Columns.Add("RelationshipType"); // 添加新列
                dt.Columns.Add("Relationship");
                dt.Columns.Add("EndNodeType");
                dt.Columns.Add("EndNode");
                foreach (var item in result)
                {
                    var dr = dt.NewRow();
                    dr.ItemArray = new[] { TableName, item.StartNode,
                        item.RelationshipType,
                        item .Relationship,
                        string.Join(',',item.EndNodeType.ToArray()),
                        item.EndNode};
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch (Exception ex)
            {
                // 处理异常
                MessageBox.Show($"连接或查询 Neo4J 数据库时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        public graphItem GetRelationsAsGraphItem<TEntity,TRelation>()
        {
            try
            {
                // 查询指定标签的节点与其他节点的关系
                var result = Client.Cypher.Match($"(n:{TableName})-[r]->(m)")
                                    .Return((n, r, m) => new
                                    {
                                        StartNode = n.As<TEntity>(),
                                        RelationshipType = r.Type(), // 获取关系类型
                                        Relationship = r.As<TRelation>(),
                                        EndNode = m.As<TEntity>(),
                                        EndNodeType = m.Labels() // 获取目标节点的标签
                                    })
                                    .ResultsAsync.Result;

                graphItem graphItem = new graphItem();

                foreach (var item in result)
                {
                    var st1 = item.RelationshipType;
                    graphItem.Add<TEntity,TRelation>(item.StartNode,item.EndNode,item.Relationship);
                }

                return graphItem;
            }
            catch (Exception ex)
            {
                // 处理异常
                MessageBox.Show($"连接或查询 Neo4J 数据库时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        public DataTable GetEntities()
        {
            try
            {
                // 查询指定标签的所有节点的属性
                var result = Client.Cypher.Match("(n:" + TableName + ")");

                var r8 = result.Return((n) => n.As<string>());
                var r9 = r8.ResultsAsync.Result;
                var r10 = r9.ToList();
                if(r10.Count==0)
                {
                    return null;
                }

                var items = new List<JObject>();
                var r11 = r10.Select(x => getData(x)).ToList();

                // 创建一个新的 DataTable
                DataTable dataTable = new DataTable();

                // 检查结果是否为空
                if (r11 != null)
                {
                    // 动态添加列到 DataTable
                    JObject firstItem = r11[0];
                    List<string> fieldName = new List<string>();
                    // 遍历 JObject 中的属性
                    foreach (var property in firstItem.Properties())
                    {
                        string key = property.Name;
                        fieldName.Add(key);
                        dataTable.Columns.Add(key, typeof(object));
                    }
                    // 将查询结果填充到 DataTable 中
                    foreach (JObject item in r11)
                    {
                        DataRow row = dataTable.NewRow();
                        foreach (var key in fieldName)
                        {
                            // 尝试获取 JObject 中指定键的值，如果值存在则赋值给 DataRow，否则赋值为 null
                            var value = item.GetValue(key);
                            row[key] = value != null ? value.ToString() : null;
                        }
                        dataTable.Rows.Add(row);
                    }
                }

                return dataTable;
            }
            catch (Exception ex)
            {
                // 处理异常
                MessageBox.Show($"连接或查询 Neo4J 数据库时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private JObject getData(string str)
        {
            var a = JsonConvert.DeserializeObject(str) as JObject;
            var dd = a["data"];
            return dd as JObject;
        }
    }
}
